package com.yiwenup.leetcode.offer;

/**
 * https://leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof/
 **/
public class No047 {
    /**
     * 执行用时：2 ms, 在所有 Java 提交中击败了98.59%的用户
     * 内存消耗：40.5 MB, 在所有 Java 提交中击败了97.90%的用户
     */
    public int maxValue(int[][] grid) {
        int x = grid.length;
        int y = grid[0].length;

        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                if (i == 0 && j == 0) continue;
                else if (i == 0) grid[i][j] += grid[i][j - 1];
                else if (j == 0) grid[i][j] += grid[i - 1][j];
                else grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]);
            }
        }

        return grid[x - 1][y - 1];
    }

    /**
     * 执行用时：2 ms, 在所有 Java 提交中击败了98.59%的用户
     * 内存消耗：40.9 MB, 在所有 Java 提交中击败了86.63%的用户
     */
    public int maxValue2(int[][] grid) {
        int x = grid.length;
        int y = grid[0].length;

        for (int i = 1; i < x; i++) {
            grid[i][0] += grid[i - 1][0];
        }

        for (int i = 1; i < y; i++) {
            grid[0][i] += grid[0][i - 1];
        }

        for (int i = 1; i < x; i++) {
            for (int j = 1; j < y; j++) {
                grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]);
            }
        }

        return grid[x - 1][y - 1];
    }
}
